<template>
  <div class="file-uploader">
    <div class="status-section">
      <h3>文件处理状态</h3>
      <div class="status-indicator" :class="status">
        <span v-if="status === 'idle'">等待文件...</span>
        <span v-else-if="status === 'received'">文件已接收</span>
        <span v-else-if="status === 'uploading'">正在上传...</span>
        <span v-else-if="status === 'success'">上传成功</span>
        <span v-else-if="status === 'error'">上传失败</span>
      </div>
    </div>

    <div v-if="fileInfo" class="file-info">
      <h4>文件信息</h4>
      <p><strong>路径:</strong> {{ fileInfo.filePath }}</p>
      <p><strong>大小:</strong> {{ formatFileSize(fileInfo.content.length) }}</p>
      <p><strong>接收时间:</strong> {{ formatTime(fileInfo.timestamp) }}</p>
      <p><strong>内容预览:</strong></p>
      <pre class="content-preview">{{ fileInfo.content.substring(0, 200) }}{{ fileInfo.content.length > 200 ? '...' : '' }}</pre>
    </div>

    <div v-if="uploadResult" class="upload-result">
      <h4>上传结果</h4>
      <div v-if="uploadResult.success" class="success">
        <p>✅ 上传成功</p>
        <p><strong>响应:</strong> {{ uploadResult.response }}</p>
      </div>
      <div v-else class="error">
        <p>❌ 上传失败</p>
        <p><strong>错误:</strong> {{ uploadResult.error }}</p>
      </div>
    </div>

    <div class="actions">
      <button 
        v-if="fileInfo && (status === 'received' || status === 'uploading')" 
        @click="uploadFile" 
        :disabled="status === 'uploading'"
        class="upload-btn"
      >
        <span v-if="status === 'uploading'">上传中...</span>
        <span v-else>上传文件</span>
      </button>
      
      <button 
        v-if="fileInfo" 
        @click="clearFile" 
        class="clear-btn"
      >
        清除文件
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

interface FileInfo {
  filePath: string
  content: string
  timestamp: string
}

interface UploadResult {
  success: boolean
  response?: any
  error?: string
}

const status = ref<'idle' | 'received' | 'uploading' | 'success' | 'error'>('idle')
const fileInfo = ref<FileInfo | null>(null)
const uploadResult = ref<UploadResult | null>(null)

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时间
const formatTime = (timestamp: string): string => {
  return new Date(timestamp).toLocaleString()
}

// 处理文件内容接收
const handleFileContentReceived = (data: FileInfo) => {
  console.log('Received file content:', data)
  fileInfo.value = data
  status.value = 'received'
  uploadResult.value = null
}

// 上传文件
const uploadFile = async () => {
  if (!fileInfo.value) return

  status.value = 'uploading'
  uploadResult.value = null

  try {
    // 这里替换为您的实际上传 API
    const response = await uploadToServer(fileInfo.value.content)
    
    uploadResult.value = {
      success: true,
      response
    }
    status.value = 'success'

    // 通知主进程上传完成
    window.electronAPI.notifyUploadCompleted({
      filePath: fileInfo.value.filePath,
      response
    })

  } catch (error) {
    console.error('Upload failed:', error)
    
    uploadResult.value = {
      success: false,
      error: error instanceof Error ? error.message : '上传失败'
    }
    status.value = 'error'

    // 通知主进程上传失败
    window.electronAPI.notifyUploadFailed({
      filePath: fileInfo.value.filePath,
      error: error instanceof Error ? error.message : '上传失败'
    })
  }
}

// 模拟上传到服务器的函数
const uploadToServer = async (_content: string): Promise<any> => {
  // 这里替换为您的实际上传逻辑
  // 例如：
  // const response = await fetch('https://your-api.com/upload', {
  //   method: 'POST',
  //   headers: {
  //     'Content-Type': 'application/json',
  //   },
  //   body: JSON.stringify({ content })
  // })
  // return await response.json()

  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 2000))
  
  // 模拟成功响应
  return {
    id: Date.now(),
    message: '文件上传成功',
    timestamp: new Date().toISOString()
  }
}

// 清除文件信息
const clearFile = () => {
  fileInfo.value = null
  uploadResult.value = null
  status.value = 'idle'
}

// 组件挂载时设置监听器
onMounted(() => {
  console.log('FileUploader component mounted, setting up listeners...')
  
  // 检查 electronAPI 是否可用
  if (window.electronAPI) {
    window.electronAPI.onFileContentReceived(handleFileContentReceived)
    console.log('File content listener set up successfully')
  } else {
    console.error('electronAPI is not available')
    status.value = 'error'
  }
})
</script>

<style scoped>
.file-uploader {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.status-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.status-indicator {
  padding: 10px;
  border-radius: 4px;
  font-weight: bold;
  text-align: center;
}

.status-indicator.idle {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status-indicator.received {
  background-color: #fff3e0;
  color: #f57c00;
}

.status-indicator.uploading {
  background-color: #e8f5e8;
  color: #388e3c;
}

.status-indicator.success {
  background-color: #e8f5e8;
  color: #388e3c;
}

.status-indicator.error {
  background-color: #ffebee;
  color: #d32f2f;
}

.file-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border-left: 4px solid #2196f3;
}

.file-info h4 {
  margin-top: 0;
  color: #2196f3;
}

.content-preview {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 100px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
}

.upload-result {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 8px;
}

.upload-result.success {
  background-color: #e8f5e8;
  border-left: 4px solid #4caf50;
}

.upload-result.error {
  background-color: #ffebee;
  border-left: 4px solid #f44336;
}

.upload-result h4 {
  margin-top: 0;
}

.actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.upload-btn, .clear-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.upload-btn {
  background-color: #2196f3;
  color: white;
}

.upload-btn:hover:not(:disabled) {
  background-color: #1976d2;
}

.upload-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.clear-btn {
  background-color: #f44336;
  color: white;
}

.clear-btn:hover {
  background-color: #d32f2f;
}
</style> 